package com.frank.libandroid;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

public class LiveDataBus {


    public static <T> MutableLiveData<T> with(Key<T> key) {
        return map.computeIfAbsent(key.key, k -> new MutableLiveData<T>() {
            AtomicBoolean pending = new AtomicBoolean(false);

            @Override
            public void observe(@NonNull LifecycleOwner owner, @NonNull Observer observer) {
                super.observe(owner, new Observer() {
                    @Override
                    public void onChanged(Object object) {
                        if (pending.compareAndSet(true, false)) {
                            observer.onChanged(object);
                        }
                    }
                });
            }

            @Override
            public void setValue(T value) {
                pending.set(true);
                super.setValue(value);
            }

        });
    }

    private static Map<Integer, MutableLiveData> map = new HashMap<>();
}
